<?php
/**
 * 《考勤明细》实现类
 *
 * @author 孙晓晔
 * @version $Id: Country.class.php 832 2010-01-06 09:17:14Z xuy $
 */
require_once(dirname(__FILE__) . '/KqUtil.class.php');

class Record extends KqUtil {
	public $tbl = Constant::tbl_kq_record;

	public $status = array(
		'-' => '请选择',
		'1' => '有效',
		'2' => '无效',
	
		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'emp' => '员工',	
		'time' => '打卡时间',

		'1' => '创建时间',
		'2' => '更新时间',
	);

	public $groupby = array(
		'-' => '请选择',
		'dept' => '部门',
		'emp' => '员工',
		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		// $controller->assign('t1', strtotime('-1 month'));
		
		$emp = array(
			// '-' => '请选择',
			'emp' => '员工',
			'oper' => '录入员',
		);
		
		$controller->assign_by_ref('emp_option', $emp);

		$controller->display($request, 'kq/record/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$date1_s = $request['date1_s'];
		$date2_s = $request['date2_s'];

		$oper_s = $this->_input($request['oper_s']);

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}
		
		if (!empty($date1_s)) {
			$where .= " AND time >= '" . $date1_s . "'";
		}

		if (!empty($date2_s)) {
			$where .= " AND time < '" . $date2_s . "'";
		}
		
		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);
		
		return $where;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$row['is_delete'] = $this->_is_delete($row);

				$data[$count] = $row;
				$count++;
			}

			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'kq/record/list');
		return true;
	}

	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}

		if ($this->_audit('111')) {
			return true;
		}

		if ($row['oper'] == $_SESSION['id']) {
			return true;
		}

		return false;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'kq/record/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$info = $request['info'];
		$info_id = $request['info_id'];

		$name = $request['name'];

		$tel = $request['tel'];
		$mobile = $request['mobile'];
		$email = $request['email'];
		$im = $request['im'];

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(info, info_id, name, tel, mobile, email, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $info, $info_id, $name, $tel, $mobile, $email);
		// debug($sql);
		$db->query($sql);

		$request['id_s'] = $db->insert_id();
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'kq/record/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$kqcard = $request['kqcard'];

		$time = $request['time'];
		$content = addslashes($request['content']);
		$status = $request['status'];

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET kqcard = '%s', time = '%s', content = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $kqcard, $time, $content, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'kq/record/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
	
		$row['week'] = $this->week($row['time']);
		// $row['date'] = $this->_date($row['t1'], $row['t2']);
	
		$row = $this->_view_t($row);
	
		return $row;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_zjm($controller, $request) {
		
		$data = $this->_ajax_zjm($request);
		echo json_encode($data);
	}

	function _ajax_zjm($request) {
		$q = $request['q'];
		
		$key = "country.ajax_" . $q;
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT id, code, zone, rate, name, zjm, continent, country FROM %s WHERE zjm LIKE '%s'";
		$sql = sprintf($fmt, $this->tbl, $q . "%");
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['continent_t'] = $this->continent[$row['continent']];

			$ret[] = $row;
		}

		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("3 day"));
		}

		return $ret;
	}

	/**
	 * 导入
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function import($controller, $request) {
		$this->pretreat($controller);
		
		$type = array(
			'-' => '请选择',
			'1' => '中控考勤机',
			'2' => '科密考勤机',
	
			'9' => '其它',
		);
		
		$controller->assign_by_ref('type_option', $type);

		$controller->display($request, 'kq/record/import');
		return true;
	}
	
	function ajax_import($controller, $request) {
	
		// debug(print_r($request, true));
	
		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			debug($file->getMessage());
		}
	
		$id = $request['id'];
	
		$type = $request['type'];
	
		if ($file->isValid()) {
			$filename = $file->upload['tmp_name'];
			debug($filename);
	
			$data = $this->_txt($id, $filename, $type);
	
			$controller->assign('id', $id);
	
			$controller->assign_by_ref('result', json_encode($data));
	
			// $this->_upload2($file, $request);
		} else {
			debug($file->getMessage());
		}
	
		// echo "1";
	
		$controller->display($request, 'kq/record/preview');
		return true;
	}
	
	function _txt($id, $file, $type) {
	
		$ret = array();
		$i = 1;
	
		$fd = fopen($file, "r");
		while (!feof($fd)) {
			$buf = $this->_to_utf8(fgets($fd));
			// echo $buf;
	
			switch($type) {
				case 1:
					// debug("269");
					$row = $this->_line_1($name, $oper, $buf);
					break;
				default:
					debug("default 308");
					break;
			}
				
			if ($row && is_array($row)) {
				$row['no'] = $i++;
				$row['ok'] = true;
				$ret[] = $row;
			}
		}
	
		fclose($fd);
	
		// debug(print_r($ret, true));
		
		return $ret;
	}
	
	function _line_1($name, $oper, $buf) {
		if (strlen($buf) < 5 || preg_match("/^#/i", $buf)) {
			return false;
		}
	
		$a = preg_split("/(\t|;)/", $buf);
	
		$ret = array();
		$ret['name'] = $this->get_alpha($a, 'b');
		$ret['emp'] = $this->get_alpha($a, 'c');
		
		if (empty($ret['emp']) || !preg_match("/^(\d+)$/i", $ret['emp'])) {
			return false;
		}
		
		$time = $this->get_alpha($a, 'd');
		
		$ret['dd'] = date('Y-m-d', strtotime($time));
		$ret['tt'] = date('H:i:s', strtotime($time));
		
		$ret['content'] = $this->get_alpha($a, 'e');
	
		$emp_x = Common::id(Constant::tbl_emp, $ret['emp']);
		if ($emp_x['name'] <> $ret['name']) {
			$ret['emp'] = 0;
		}
	
		return $ret;
	}
	
	function get_alpha($a, $c) {
		$i = $this->alpha2num($c);
		$s = $a[$i];
	
		$s = trim($s);
		if (empty($s)) {
			return '';
		}
	
		$s = preg_replace("/[\"|\'|,]+/i", "", $s);
	
		return $s;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function importPost($controller, $request) {
		$this->pretreat($controller);

		$this->_update($request['data']);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _update($data) {
		$data = json_decode($data, true);
	
		$oper = $_SESSION['id'];
			
		$db = newdb($this->dsn_w);
		while (list($k, $v) = each($data)) {
				
			if (empty($v['name']) || empty($v['emp'])) {
				continue;
			}
				
			if ($v['ok'] == '0') {
				continue;
			}
				
			$emp = $v['emp'];
			$office = $this->_office($emp);
			$dept = $this->_emp_dept($emp);
			
			$time = sprintf("%s %s", $v['dd'], $v['tt']);
				
			$fmt = "SELECT * FROM %s WHERE AND emp = '%s' AND time = '%s'";
			$sql = sprintf($fmt, $this->tbl, $file, $emp, $time);
			debug($sql);
			$result = $db->query($sql);
			if ($row = $db->fetch_array($result)) {
				$fmt = "UPDATE %s SET office = '%s', dept = '%s', content = '%s', modifytime = now() WHERE id = '%s'";
				$sql = sprintf($fmt, $this->tbl, $office, $dept, $v['content'], $row['id']);
			} else {
				$fmt = "INSERT INTO %s(office, dept, emp, time, content, oper, createtime, modifytime)";
				$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
				$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $time, $v['content'], $oper);
			}
				
			debug($sql);
			$db->query($sql);
		}
	}

	var $info_dir = 'kq';

	function ajax_upload($controller, $request) {
		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			die($file->getMessage());
		}

		$type = $request['type'];
		$oper = $request['oper'];

		if ($file->isValid()) {
			$filename = $file->upload['tmp_name'];
			debug($filename);
			
			if ($type == '1') {
				// $this->_xls_1($buf, $oper);
				$this->_txt($type, $oper, $filename);
			} else {

				$this->_xls($type, $filename, $oper);
			}
		}

		echo "1";
		return true;
	}

	/**
	 * 导入考勤信息
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function z($controller, $request) {
		$file = "/home/sunxy/kq.txt";
		$this->_txt_1('101', $file);

		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}

	function _is_time($s) {
		$s = trim($s);
		if (preg_match("/^(\d{1,2}):(\d{1,2})$/i", $s)) {
			return true;
		}

		if (preg_match("/^(\d{1,2}):(\d{1,2}):(\d{1,2})$/i", $s)) {
			return true;
		}

		return false;
	}

	function _xls($type, $file, $oper) {
		require_once APP_LIB . 'excel_class.php';

		Read_Excel_File($file, $return);
		// debug(print_r($return, true));

		$a = array_keys($return);
		
		debug(print_r($a, true));
		while (list($k, $v) = each($a)) {
			$buf = $return[$v];
			
			// debug(print_r($buf, true));

			// $this->_xls_1($buf, $oper);
			
			if ($type == '1') {
				// $this->_xls_1($buf, $oper);
				$this->_txt_1($buf, $oper);
			}
			
			if ($type == '2') {
				$this->_xls_2($buf, $oper);
			}
		}
	}

	function _emp($name, $kqcard) {
		$emp = $this->_emp_kqcard($kqcard);
		if ($emp) {
			return $emp;
		}
			
		$emp = $this->_emp_name($name);
		if ($emp) {
			return $emp;
		}
			
		return false;
	}

	function _emp_kqcard($kqcard) {
		$key = "emp.kqcard_" . $kqcard;
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb(Constant::tbl_emp);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND kqcard = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, Constant::tbl_emp, $kqcard);
		debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) == 0) {
			return false;
		}

		$ret = $db->fetch_array($result);

		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}

	function _emp_name($name) {
		$key = "emp.name_" . md5($name);
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb(Constant::tbl_emp);
		$fmt = "SELECT * FROM %s WHERE name = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, Constant::tbl_emp, $name);
		debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) == 0) {
			return false;
		}

		$ret = $db->fetch_array($result);

		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}

	function group($controller, $request) {
		$this->pretreat_group($controller);

		// $controller->assign('t1', strtotime('-1 month'));
		$controller->assign('t2', strtotime('+1 day'));
		
		$controller->assign('result_s', "300");

		$controller->display($request, 'kq/record/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	function groupby_dd($px) {
		if ($px == '1') {
			return "DATE_FORMAT(time, '%Y-%m-%d %H')";
		}

		if ($px == '2') {
			return "DATE_FORMAT(time, '%Y-%m-%d')";
		}

		if ($px == '3') {
			return "DATE_FORMAT(time, '%Y-%m')";
		}

		return $px;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} else {

			$row = $this->_name_t($row, $px);
		}

		return $row;
	}

	function t($controller, $request) {
		$this->pretreat($controller);

		$a = array('0005866088', '2010-3-2', '4', '7:57:42', '12:01:17', '13:56:19', '18:04:42');

		print_r($a);

		logdate($controller, $request);
		return true;
	}
}
?>